package cn.itcast.bos.web.action;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.service.FixedAreaService;
import cn.itcast.bos.web.action.common.BaseAction;
import cn.itcast.crm.domain.Customer;

@Controller
@ParentPackage("json-default")
@Namespace("/")
@Actions
@Scope("propotype")
public class FixedAreaAction extends BaseAction<FixedArea> {
	// 注入service
	@Autowired
	private FixedAreaService fixedAreaService;

	// 我们直接继承BaseAction这样可以简化我们的开发
	@Action(value = "fixedArea_save", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/fixed_area.html") })
	public String Save() {
		// 直接使用service
		fixedAreaService.save(model);
		return SUCCESS;
	}

	// 分页查询
	private Integer rows;
	private Integer page;

	public void setRows(Integer rows) {
		this.rows = rows;
	}

	public void setPage(Integer page) {
		this.page = page;
	}

	@Action(value = "fixedArea_pageQuery", results = { @Result(name = "success", type = "json") })
	public String pageQuery() {
		Pageable pageable = new PageRequest(page - 1, rows);
		Specification<FixedArea> specifications = new Specification<FixedArea>() {

			@Override
			public Predicate toPredicate(Root<FixedArea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> list = new ArrayList<Predicate>();
				if (StringUtils.isNoneBlank(model.getId())) {
					Predicate p1 = cb.like(root.get("id").as(String.class), "%" + model.getId() + "%");
					list.add(p1);
				}
				if (StringUtils.isNoneBlank(model.getCompany())) {
					Predicate p2 = cb.like(root.get("company").as(String.class), "%" + model.getCompany() + "%");
					list.add(p2);
				}
				return cb.and(list.toArray(new Predicate[0]));
			}
		};
		Page<FixedArea> pageList = fixedAreaService.findPageData(specifications, pageable);
		// 返回的数据写成我们想要的数据
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("totle", pageList.getTotalElements());
		result.put("rows", pageList.getContent());
		// 转为json数据，
		ActionContext.getContext().getValueStack().push(result);
		return SUCCESS;
	}

	// 关联用户
	@Action(value = "findNOAssociation_Customer", results = { @Result(name = "success", type = "json") })
	public String findNoAssociationCustomer() {
		Collection<? extends Customer> collection = WebClient
				.create("http://localhost:8889/crm_management/service/customerService/noassocationcustomer")
				.accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
		ActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	@Action(value = "findHasAssociation_CustomerToFixedAreaId", results = { @Result(name = "success", type = "json") })
	public String findHasAssociationCustomerToFixedAreaId() {
		Collection<? extends Customer> collection = WebClient
				.create("http://localhost:8889/crm_management/service/customerService/hasassocationfixedareacustomer/"
						+ model.getId())
				.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON).getCollection(Customer.class);
		ActionContext.getContext().getValueStack().push(collection);
		return SUCCESS;
	}

	// 将未关联用户进行关联
	private String[] customerIds;

	public void setCustomerIds(String[] customerIds) {
		this.customerIds = customerIds;
	}

	@Action(value = "fixedArea_associationCustomersToFixedArea", results = {
			@Result(name = "success", type = "redirect", location = "/pages/base/fixed_area.html") })
	// 首先将我们的数据进行切分
	public String fixedArea_associationCustomersToFixedArea() {
		String customerIdStr = StringUtils.join(customerIds, ",");
		WebClient
				.create("http://localhost:8889/crm_management/service/customerService/assocationcustomertofixedarea?CustomerIdStr="
						+ customerIdStr + "&fixedAreaId=" + model.getId())
				.put(null);

		return SUCCESS;
	}
	//关联快递员和上下半时间
	//这里需要使用两个数据
	private Integer courierId;
	private Integer takeTimeId;
	public void setCourierId(Integer courierId) {
		this.courierId = courierId;
	}
	public void setTakeTimeId(Integer takeTimeId) {
		this.takeTimeId = takeTimeId;
	}

	@Action(value="fixedArea_associationCourierToFixedArea",results={@Result(name="success",type="redirect",location="/pages/base/fixed_area.html")})
	public String fixedArea_associationCourierToFixedArea(){
		//将我们的数据传到业务层
		fixedAreaService.fixedArea_associationCourierToFixedArea(model,courierId,takeTimeId);
		return SUCCESS;
	}
	//查询所有
	@Action(value = "fixedarea_findAll", results = { @Result(name = "success", type = "json") })
	public String fixedarea_findAll(){
		List<FixedArea> listFixedArea = fixedAreaService.findAllFixedArea();
		ActionContext.getContext().getValueStack().push(listFixedArea);
		return SUCCESS;
	}
}
